from .tiangan import Gan
from .dizhi import Zhi


class ZhangSheng:
    """
    十二长生
    """
    _cache = {}
    _inited = False

    def __new__(cls, gan, zhi, name):
        if cls._inited:
            raise RuntimeError(f'{cls.__name__} 已经加载，不能直接实例化，请使用 {cls.__name__}.get_item')
        if (gan, zhi) in cls._cache:
            return cls._cache[(gan, zhi)]
        else:
            self = super().__new__(cls)
            cls._cache[(gan, zhi)] = self
            return self

    def __init__(self, gan, zhi, name):
        self.gan = Gan.get_item(gan)
        self.zhi = Zhi.get_item(zhi)
        self.name = name

    @classmethod
    def init_zhangsheng(cls, zhangsheng_grid):
        """
        初始化的时候调用一次
        """
        for (gan, zhi), name in zhangsheng_grid.items():
            cls(gan, zhi, name)
        cls._inited = True

    @classmethod
    def get_item(cls, gan, zhi):
        """
        返回指定的对象
        """
        return cls._cache[(gan, zhi)]

    def __str__(self):
        return self.name
